import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { userProfilesApi } from "@/components/Api";

//再次请求有户信息
let token = localStorage.getItem("token");
if (token) {
  //请求
  userProfilesApi().then((res) => {
    if (res.code == 0) {
      console.log(res.data);
      //存取用户信息 到仓库 显示到TopBBar
      const userStore = useUserStore();
      userStore.userObject = res.data;
      userStore.token = token as string;
    }
  });
}
export const useUserStore = defineStore("USER", {
  state() {
    return {
      token: "",
      //是否登录
      isLogin: false,
      //用户信息
      userObject: {
        cartTotal: 0, //鸡腿数
        userInfo: {
          username: "", //账号
          nickName: "", //用户名
          phone: "", //电话
          coin: null, //积分
          headImg: "", //头像
        },
      },
    };
  },
  actions: {
    changeToken(payload?: string) {
      this.token = payload as string;
    },
    changeShowLogin() {
      this.isLogin = true;
    },
    //初始化用户信息
    resetUser() {
      console.log(111);
      this.isLogin = false;
      this.userObject.cartTotal = 0;
      this.token = "";
      this.userObject.userInfo = {
        username: "", //账号
        nickName: "", //用户名
        phone: "", //电话
        coin: null, //积分
        headImg: "", //头像
      };
    },
  },
});
